var common = require('../../utils/common.js');
var ajax = require('../../utils/ajax.js');
var Base = require('../../common/CmptBase.js');

/**
 * 下拉选择组
 * @param {[type]} options.page  [description]
 * @param {[type]} options.scope [description]
 * @param {[type]} options.      [description]
 */
var Dropdown = function({
  page,
  scope,
}) {
  Base.apply(this, arguments);
}

common.extend(Dropdown, Base);

Object.assign(Dropdown.prototype, {
  /**
   * 初始化
   * @param  {[type]} optinos [description]
   * @return {[type]}         [description]
   */
  init(optinos) {
    var options = optinos || {};
    var {
      tabs = [], contents = []
    } = optinos

    this._options = optinos;

    contents = contents.map(function(arr) {
      return [{
        id: 0,
        option: '全部',
        _selected: true
      }].concat(arr);
    });

    wx.getSystemInfo({
      success: (res) => {
        const {
          windowHeight,
          windowWidth
        } = res;

        this.setData({
          contentHei: windowHeight * 0.75
        });
      },
    });

    this.setData({
      tabs,
      contents,
      selectedIndex: -1,
      contentsVisible: false,
    });

    return this;
  },

  /**
   * 选择tab
   * @param  {[type]} e [description]
   * @return {[type]}   [description]
   */
  switchTab(e) {
    var lastIndex = this.getData('selectedIndex');
    var lastVisible = this.getData('contentsVisible');
    var curIndex = e.currentTarget.dataset.index;
    var curVisible = false;

    if (!lastVisible) {
      curVisible = true;
    } else {
      curVisible = curIndex != lastIndex;
    }

    this.setData({
      contentsVisible: curVisible,
      selectedIndex: curIndex
    });
  },

  /**
   * 选择选项
   * @param  {[type]} e [description]
   * @return {[type]}   [description]
   */
  selectOption(e) {
    var item = e.currentTarget.dataset.item;
    var selectedIndex = this.getData('selectedIndex');
    var tabs = this.getData('tabs');
    var contents = this.getData('contents');
    var options = contents[selectedIndex];

    options && options.forEach(function(option) {
      if (option.id == item.id) {
        tabs[selectedIndex] = option.option;
      }
      option._selected = option.id == item.id;
    });

    this.setData({
      contents
    });

    setTimeout(() => {
      this.setData({
        contentsVisible: false
      })
    }, 300)


    this._options.selectOption && this._options.selectOption(selectedIndex, item);
  },

  /**
   * 隐藏下拉
   * @return {[type]} [description]
   */
  hide() {
    this.setData({
      contentsVisible: false,
      selectedIndex: -1,
    });
  },

});

module.exports = Dropdown;